package recite.word.service.base.common.config;

import cn.hutool.core.util.ArrayUtil;
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import recite.word.service.base.common.interceptor.UserInterceptor;


/**
 * 用户拦截配置
 */
@Configuration
@EnableKnife4j
public class UserInterceptorConfig implements WebMvcConfigurer {
    @Value("${recite.swagger.enable:false}")
    private Boolean swaggerEnable;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) { // 添加资源的白名单
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/static/");
        if (swaggerEnable){
            registry.addResourceHandler("doc.html")
                    .addResourceLocations("classpath:/META-INF/resources/");
        }
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    @Autowired
    private UserInterceptor userInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //注册interceptor拦截器,用自己的userInterceptor拦截器
        InterceptorRegistration registration = registry.addInterceptor(userInterceptor);
        registration.addPathPatterns("/**"); //所有路径都被拦截
        //先全部放行
        String[] whitelist = new String[]{//client放行接口
                "/test/**", //测试桩
                "/client/login/*", //和登录有关的接口
                "/client/word/code", //验证码
                "/client/file/*", //文件操作
                "/**/*.html","/**/*.js","/**/*.css","/client/file/translate"};
        if (swaggerEnable){
            // 对swagger的请求不进行拦截
            String[] excludePatterns = new String[]{"/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**",
                    "/api", "/api-docs", "/api-docs/**", "/doc.html/**"};
            whitelist = ArrayUtil.addAll(whitelist, excludePatterns);
        }
        //白名单
        registration.excludePathPatterns(whitelist);
    }
}
